<?php

    /**
     * XML parser
     *
     * @package      Core
     * @subpackage   Parser
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
	class Core_Parser_XML
	{

	////////////////////////////////////////////////////////////////////////////
	//                                 Methods                                //
	////////////////////////////////////////////////////////////////////////////

        /**
        * The main function for converting to an XML document.
        * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
        *
        * @param        array               $data
        * @param        string              $rootNodeName - what you want the root node to be - defaultsto data.
        * @param        SimpleXMLElement    $xml - should only be used recursively
        * @return       SimpleXMLElement
        */
		public static function fromArray(array $data, $rootNodeName = 'data', array $handlers = null, $xml = null)
        {
            if (ini_get('zend.ze1_compatibility_mode') == 1) {
                ini_set ('zend.ze1_compatibility_mode', 0);
            }

            if ($xml == null) {
                $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><'. $rootNodeName .' />');
            }

            foreach ($data as $key => $value) {
                if (is_numeric($key)) {
                    $key = 'item';
                }

                if (isset($handlers[$key])) {
                    $value = call_user_func($handlers[$key], $data);
                }

                if (is_array($value)) {
                    $node = $xml->addChild($key);
                    self::fromArray($value, $rootNodeName, $handlers, $node);

                } else {
                    if (is_bool($value)) {
                        $value = ($value) ? 'true' : 'false';
                    }

                    if (!empty($value)) {
                        $value = '<![CDATA[' . $value . ']]>';
                    }
                    $xml->addChild($key, $value);
                }
            }

            return $xml;
        }
	}
